var express = require('express');
var router = express.Router();
const UserModel = require('../../models/UserModel')
const md5 = require('md5')

// 导入jsonwebtoken
const jwt = require('jsonwebtoken')

// 导入配置项
const {secret} = require('../../config/config')


// 登录提交
router.post('/login', (req, res) => {
    let { username, password } = req.body
    UserModel.findOne({ username: username, password: md5(password) }, (err, data) => {
        if (err) {
            return res.json({
                code: '2001',
                msg: '数据库读取失败',
                data: null
            })
        }
        console.log(data)
        if (!data) {
            return res.json({
                code: '2002',
                msg: '账号或密码错误',
                data: null
            })
        }

        // 创建当前用户的token
        let token = jwt.sign({
            username: data.username,
            _id: data._id
        }, secret, {
            expiresIn: 60 * 60 * 24 * 7
        })
        // 响应token
        res.json({
            code: "0000",
            msg: "登陆成功",
            data: token
        })

        // 登录成功响应
        res.render('success', { msg: '登录成功', url: '/account' })
    })
})

// 退出登录
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', { msg: '退出登录成功', url: '/login' })
    })
})

module.exports = router;
